import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Modal, Card, Select, message, Popconfirm } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { IArea } from 'api/Area';
import { MinusCircleOutlined } from '@ant-design/icons';
import { ICamera, saveBatchCamerasApi, deleteCameraApi } from 'api/Camera';
import { useRequest, useToggle } from 'ahooks';

interface ICameraEdit {
    id: number;
    form: FormInstance | undefined;
    originData?: ICamera;
}
interface CameraProps {
    areas: IArea[];
    camera: ICameraEdit;
    updateCamera: any;
}
let formList: any = [];
const Camera = (props: CameraProps) => {
    const { camera, updateCamera, areas } = props;
    const [confirmVisible, { toggle: toggleConfirmVisible }] = useToggle(false);
    const [form] = Form.useForm();
    const { run: deleteCameraRun } = useRequest(deleteCameraApi, {
        manual: true,
    });
    useEffect(() => {
        if (camera.originData) {
            form.setFieldsValue(camera.originData);
            formList.push(form);
        } else {
            updateCamera({ ...camera, form });
        }
    }, []);
    /** 点击减号图标 */
    const handleVisibleChange = () => {
        if (camera.originData) {
            // 已存在摄像机
            toggleConfirmVisible(true);
        } else {
            // 新增加的摄像机
            updateCamera(camera, 'delete');
        }
    };
    const confirmDelete = async () => {
        await deleteCameraRun([camera.id]);
        message.success('删除摄像机成功');
        updateCamera(camera, 'delete');
    };
    const cancel = () => {
        toggleConfirmVisible(false);
    };

    return (
        <Card className="mb10" hoverable>
            <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                <Form.Item label="IP地址">
                    <Form.Item name="ipAddress" rules={[{ required: true, message: '请输入IP地址' }]} noStyle>
                        <Input
                            placeholder="请输入IP地址"
                            style={{ width: 270, marginRight: 10 }}
                            disabled={Boolean(props.camera.originData)}
                            allowClear
                        />
                    </Form.Item>
                    <Popconfirm
                        title="确定删除该设备?"
                        visible={confirmVisible}
                        onVisibleChange={handleVisibleChange}
                        onConfirm={confirmDelete}
                        onCancel={cancel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <MinusCircleOutlined className="font-20" />
                    </Popconfirm>
                </Form.Item>
                <Form.Item label="设备区域" name="areaId" rules={[{ required: true, message: '请选择设备区域' }]}>
                    <Select allowClear>
                        {areas.map((area) => (
                            <Select.Option key={area.id} value={area.id || -1}>
                                {area.name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="设备账号" name="account" rules={[{ required: true, message: '请输入设备账号' }]}>
                    <Input placeholder="请输入设备账号" allowClear />
                </Form.Item>
                <Form.Item label="设备密码" name="password" rules={[{ required: true, message: '请输入设备密码' }]}>
                    <Input placeholder="请输入设备密码" allowClear />
                </Form.Item>
            </Form>
        </Card>
    );
};

interface EditProps {
    visible: boolean;
    setVisible: Function;
    areas: IArea[];
    editCameras: ICamera[];
    isEdit: boolean;
}
const CameraEdit = (props: EditProps) => {
    const [cameraList, setCameraList] = useState<ICameraEdit[]>([]);
    const [isEdit, setIsEdit] = useState(false);
    const { run: saveBatchCamerasRun, loading: saveBatchCamerasLoading } = useRequest(saveBatchCamerasApi, {
        manual: true,
    });
    useEffect(() => {
        if (!props.visible) {
            // 关闭弹框清除数据
            setCameraList([]);
            return;
        }
        console.log('editCameras', props.editCameras);
        formList = [];
        let timer: any;
        if (props.visible) {
            if (props.isEdit) {
                const editCameraList = props.editCameras.map((camera) => ({
                    id: camera.id,
                    form: undefined,
                    originData: camera,
                }));
                setCameraList(editCameraList);
                timer = setInterval(() => {
                    // 轮询检测form是否更新到CameraEdit
                    console.log(formList.length, editCameraList.length);
                    if (formList.length === editCameraList.length) {
                        console.log(formList);
                        const result = editCameraList.map((camera, index) => {
                            camera.form = formList[index];
                            return camera;
                        });
                        setCameraList(result);
                        clearInterval(timer);
                    }
                });
            } else {
                setCameraList([
                    {
                        id: Math.random(),
                        form: undefined,
                    },
                ]);
            }
        }
        setIsEdit(props.isEdit);
        return () => {
            clearInterval(timer);
        };
    }, [props.visible]);

    /** 点击确认 */
    const okClick = async () => {
        let validates: any = [];
        cameraList.map((camera) => validates.push(camera.form?.validateFields()));
        await Promise.all(validates); // 校验全部摄像头表单
        const result = cameraList.map((camera) => {
            if (camera.originData) {
                return {
                    id: camera.id,
                    ...camera.form?.getFieldsValue(),
                };
            }
            return { ...camera.form?.getFieldsValue() };
        });
        console.log(result);
        saveBatchCamerasRun(result).then(() => {
            props.setVisible(false);
            message.success('修改成功');
        });
    };
    const cancelClick = () => {
        props.setVisible(false);
    };
    /** 添加摄像头 */
    const addCamera = () => {
        setCameraList([...cameraList, { id: Math.random(), form: undefined }]);
    };
    /** 更新单个摄像头 */
    const updateCamera = (newCamera: any, type: string) => {
        if (type === 'delete') {
            setCameraList(cameraList.filter((camera) => camera.id !== newCamera.id));
            return;
        }
        const result = cameraList.map((camera) => {
            return camera.id === newCamera.id ? newCamera : camera;
        });
        setCameraList(result);
    };
    return (
        <Modal
            visible={props.visible}
            title={isEdit ? '设备编辑' : '设备添加'}
            okText="确定"
            cancelText="取消"
            onOk={okClick}
            onCancel={cancelClick}
            bodyStyle={{ height: 500, overflowY: 'auto' }}
            destroyOnClose={true}
            okButtonProps={{ disabled: cameraList.length === 0 || saveBatchCamerasLoading }}
        >
            {cameraList.map((camera) => (
                <Camera key={camera.id} areas={props.areas} updateCamera={updateCamera} camera={camera} />
            ))}
            <Button type="primary" onClick={addCamera} block>
                添加
            </Button>
        </Modal>
    );
};
export default CameraEdit;
